Given an array of words and a length L, format the text such that each line has exactly L characters and is fully justified on both the left and the right. Words should be packed in a greedy approach; that is, pack as many words as possible in each line. Add extra spaces when necessary so that each line has exactly L characters.
Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line does not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right. For the last line of text and lines with one word only, the words should be left justified with no extra space inserted between them.
Example
For
words = ["This", "is", "an", "example", "of", "text", "justification."]
and L = 16, the output should be
textJustification(words, L) = ["This is an",
"example of text",
"justification. "]
In [88]:
def textJustification(words, max_width):
res, cur, num_letters = [], [], 0
for w in words:
if num_letters + len(w) + len(cur) > max_width:
for i in range(max_width - num_letters):
cur[i%(len(cur) -1 or 1)] += " "
res.append(''.join(cur))
cur, num_letters = [], 0
cur += [w]
num_letters += len(w)
return res + [' '.join(cur).ljust(max_width)]
In [90]:
textJustification( ["this", "is", "an", "example", "of", "some", "words"], 13)
Out[90]:
In [81]: